<template>
  <el-row style="min-width: 1500px">
    <el-col :span="24">
      <div class="program_flex_box x-flex">
        <div class="wrap_left_grouping">
          <div class="wrap_left_grouping--head-title x-flex x-row-between">
            <text>节目分组</text>
            <el-button text type="primary" @click="addBut"
              ><img
                class="x-m-r-6"
                v-has="'programGrouping'"
                src="@/assets/Add.svg"
              />新增分组
            </el-button>
          </div>
          <el-dialog v-model="dialogVisible" @close="clearAd" width="30%">
            <template #header="{ titleId, titleClass }">
              <div class="my-header">
                <h4
                  :id="titleId"
                  :class="titleClass"
                  style="display: flex; align-items: center"
                >
                  <div class="add"></div>
                  <div style="margin: 0 5px">{{ userINfo }}</div>
                </h4>
              </div>
            </template>
            <el-input
              v-model="addTreeName"
              placeholder="请输入分组名称"
              maxlength="20"
              @input="btnAdd"
            />
            <div v-if="addIN" style="color: red">分组名称不能为空</div>
            <template #footer>
              <span class="dialog-footer">
                <el-button type="primary" @click="onAddTreeName">
                  添加
                </el-button>
              </span>
            </template>
          </el-dialog>
          <div class="wrap_left_grouping--content-area">
            <el-tree
              :data="trees"
              default-expand-all
              @node-click="nodeClick"
              :expand-on-click-node="false"
            >
              <template #default="{ node, data }">
                <div class="x-flex x-row-between x-flex1">
                  <span v-if="!data.isEditNode">{{ node.label }}</span>
                  <el-dropdown v-if="!data.isAddNode">
                    <span style="outline: none">
                      <el-icon color="#a8abb2"><MoreFilled /></el-icon>
                    </span>
                    <template #dropdown>
                      <el-dropdown-menu>
                        <el-dropdown-item
                          @click.stop="addAllNode(node, data)"
                          v-has="'facility-Addgroup'"
                          >创建子分组
                        </el-dropdown-item>
                        <el-dropdown-item
                          @click.stop="editStop(node, data)"
                          v-has="'facility-Editgroup'"
                          >重命名
                        </el-dropdown-item>
                        <el-dropdown-item
                          @click.stop="delAllNode(node, data)"
                          v-has="'facilityDelete'"
                          >删除
                        </el-dropdown-item>
                      </el-dropdown-menu>
                    </template>
                  </el-dropdown>
                </div>
                <br />
              </template>
            </el-tree>
          </div>
        </div>
        <div class="wrap_right_list">
          <div class="wrap_right_list--head-title">
            <text>节目管理</text>
          </div>
          <div class="wrap_right_list--head-operation x-scroll">
            <div class="x-flex">
              <div class="x-m-r-12">
                <el-button
                  size="large"
                  type="primary"
                  @click="Addpass"
                  v-has="'Addprogram'"
                  >新增节目
                </el-button>
                <el-dialog
                  v-model="isUploadMaterial"
                  width="30%"
                  @close="clearAds"
                >
                  <template #header="{ titleId, titleClass }">
                    <div class="my-header">
                      <h4
                        :id="titleId"
                        :class="titleClass"
                        style="display: flex; align-items: center"
                      >
                        <div class="add"></div>
                        <div style="margin: 0 5px">新增节目</div>
                      </h4>
                    </div>
                  </template>
                  <div class="-dialog-input">
                    <el-form
                      ref="ruleFormRef"
                      :model="formInline"
                      :rules="rules"
                      label-position="right"
                      label-width="80px"
                    >
                      <el-form-item label="名称" prop="programName">
                        <el-input
                          v-model="formInline.programName"
                          placeholder="请填写节目名称"
                        />
                      </el-form-item>
                      <el-form-item label="类型" prop="programType">
                        <el-select
                          v-model="formInline.programType"
                          placeholder="请选择类型"
                        >
                          <el-option label="单屏" value="0" />
                        </el-select>
                      </el-form-item>
                      <el-form-item label="分辨率" prop="programResolution">
                        <el-select
                          v-model="formInline.programResolution"
                          placeholder="请选择分辨率"
                        >
                          <el-option label="自定义分辨率" value="zdy" />
                          <el-option
                            v-for="item in options"
                            :key="item.value"
                            :label="item.label"
                            :value="item.value"
                          />
                        </el-select>
                      </el-form-item>
                      <el-form-item
                        v-if="formInline.programResolution == 'zdy'"
                        label="屏幕尺寸"
                        prop="programCustom"
                      >
                        <div class="-addDialogFormInput x-flex">
                          <el-input
                            v-model="formInline.wide"
                            placeholder="宽"
                            maxlength="4"
                            minlength="3"
                          />
                          <span style="padding-left: 3px">px</span>
                          <el-icon class="x-m-l-8 x-m-r-8">
                            <Close />
                          </el-icon>
                          <el-input
                            v-model="formInline.High"
                            placeholder="高"
                            minlength="3"
                            maxlength="4"
                          />
                          <span style="padding-left: 3px">px</span>
                        </div>
                      </el-form-item>
                    </el-form>
                  </div>
                  <template #footer>
                    <span class="dialog-footer">
                      <el-button @click="isUploadMaterial = false"
                        >取消</el-button
                      >
                      <el-button
                        type="primary"
                        @click="submitProgramForm(ruleFormRef)"
                      >
                        新建
                      </el-button>
                    </span>
                  </template>
                </el-dialog>
              </div>
              <el-dropdown ref="releaseDelete" trigger="contextmenu">
                <el-button
                  size="large"
                  @click="releaseTable(tableData)"
                  v-has="'facilityAdver'"
                  >发布广告
                </el-button>
                <template #dropdown>
                  <div class="x-p-8">请选择节目</div>
                </template>
              </el-dropdown>
              <el-dropdown
                ref="dropdownGrouping"
                class="x-m-l-12 x-m-r-12"
                trigger="contextmenu"
              >
                <el-button
                  v-has="'programBatchChange'"
                  size="large"
                  @click="changeGrouping(tableData)"
                  >更改分组
                </el-button>
                <template #dropdown>
                  <div class="x-p-8">请选择节目</div>
                </template>
              </el-dropdown>
              <el-dropdown ref="dropdownDelete" trigger="contextmenu">
                <el-button
                  size="large"
                  @click="deleteTable(tableData)"
                  v-has="'programBatchDelete'"
                  >删除
                </el-button>
                <template #dropdown>
                  <div class="x-p-8">请选择节目</div>
                </template>
              </el-dropdown>
              <el-dialog
                v-model="isGroupingDialog"
                @close="verify"
                :close-on-press-escape="false"
                title="选择分组"
                width="25%"
              >
                <template #header="{ titleId, titleClass }">
                  <div class="my-header">
                    <h4
                      :id="titleId"
                      :class="titleClass"
                      style="display: flex; align-items: center"
                    >
                      <div class="add"></div>
                      <div style="margin: 0 5px">选择分组</div>
                    </h4>
                  </div>
                </template>
                <el-form
                  ref="equipFormRef"
                  :model="equipForm"
                  :rules="equipRules"
                  label-position="left"
                  label-width="70px"
                >
                  <el-form-item label="分组" prop="eEquipName">
                    <div class="-addDialogFormInput e-l-cascader">
                      <el-cascader
                        ref="cascader"
                        v-model="equipForm.eEquipName"
                        :options="trees"
                        :props="regionProps"
                        clearable
                        placeholder="请选择分组"
                        @change="getCheckedNode"
                      />
                    </div>
                  </el-form-item>
                </el-form>
                <template #footer>
                  <span>
                    <el-button @click="isGroupingDialog = false"
                      >取消</el-button
                    >
                    <el-button
                      type="primary"
                      @click="submitChangeGrouping(equipFormRef)"
                    >
                      确定
                    </el-button>
                  </span>
                </template>
              </el-dialog>
            </div>
            <div class="-row--search">
              <el-select
                v-model="selectValue"
                placeholder="请选择分辨率"
                size="large"
                style="width: 200px"
                clearable
                @clear="closeClick()"
              >
                <el-option label="全部分辨率" value="" @click="clickSelct" />
                <el-option
                  v-for="item in options"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                  @click="select(item)"
                />
              </el-select>
              <el-date-picker
                v-model="dateValue"
                class="x-m-l-10 x-m-r-10"
                end-placeholder="结束日期"
                size="large"
                start-placeholder="开始日期"
                style="width: 300px"
                type="daterange"
                @change="TimeClcik(dateValue)"
                @clear="handeclear"
                unlink-panels
                clearable
              />
              <el-input
                v-model="search"
                :suffix-icon="Search"
                placeholder="输入素材名或用户名"
                size="large"
                style="width: 240px; cursor: pointer"
                @change="inputClick"
                clearable
              />
            </div>
          </div>
          <div class="wrap_right_list--table-content">
            <el-table
              ref="multipleTableRef"
              :data="tableData"
              :header-cell-style="{ background: '#F6F7F9' }"
              :row-style="{ height: '64px' }"
              height="calc(90vh - 220px)"
              style="width: 100%; z-index: 1"
              @selection-change="handleSelectionChange"
            >
              <template #empty>
                <div class="no-data">
                  <el-empty
                    :image="require('../../assets/nothave.png')"
                    style="margin-top: 30%"
                  >
                  </el-empty>
                </div>
              </template>
              <el-table-column type="selection" width="40" />
              <el-table-column
                label="节目名称"
                min-width="200"
                show-overflow-tooltip
              >
                <template #default="{ row }">
                  <div class="x-flex">
                    <img
                      v-if="row.thumbnail"
                      :src="row.thumbnail"
                      style="width: 28px; height: 28px; margin-right: 8px"
                    />
                    <div v-if="!row.thumbnail">
                      <img
                        src="../../assets/wat.png"
                        style="width: 28px; height: 28px; margin-right: 8px"
                      />
                    </div>
                    <el-text v-if="!row.isFile" style="max-width: 70%" truncated
                      >{{ row.programName }}
                    </el-text>
                    <el-input
                      v-show="row.isFile"
                      v-model="row.programName"
                      class="file-child-node"
                      @change="handleFileName(row)"
                      @keyup.enter.stop.native="row.isFile = false"
                      @click.stop
                    />
                    <!-- <span v-if="!row.isFile" class="--table-column-icon">
                  <el-icon color="#A8ADB2" @click.stop="row.isFile = true"
                    ><EditPen
                  /></el-icon>
                </span> -->
                    <span v-if="!row.isFile" class="--table-column-icon">
                      <el-icon color="#A8ADB2" @click.stop="copyFileName(row)">
                        <CopyDocument />
                      </el-icon>
                    </span>
                  </div>
                </template>
              </el-table-column>
              <el-table-column label="分辨率" width="130">
                <template #default="{ row }">
                  <div v-if="row.wideResolution">
                    {{ row.wideResolution }} X {{ row.longResolution }}
                  </div>
                </template>
              </el-table-column>
              <el-table-column label="文件大小" width="130">
                <template #default="{ row }">
                  <div>{{ row.programSize }}M</div>
                </template>
              </el-table-column>
              <el-table-column label="类型" width="120">
                <template #default="{ row }">
                  <div v-if="row.programType == 0">单屏</div>
                </template>
              </el-table-column>
              <el-table-column
                label="创建时间"
                property="creationDate"
                width="200"
              />
              <el-table-column
                label="上传用户"
                property="lastUpdatedAccount"
                show-overflow-tooltip
                width="130"
              />
              <el-table-column
                label="操作"
                width="120"
                style="display: flex; align-items: center"
              >
                <template #default="{ row }">
                  <!-- <el-button size="small" text type="primary">发布</el-button> -->
                  <!-- <el-button size="small" text type="primary">预览</el-button> -->
                  <div style="display: flex; align-items: center">
                    <el-button
                      size="small"
                      text
                      type="primary"
                      @click="copyTableObj(row)"
                      style="margin: 0 -10px"
                      >复制
                    </el-button>
                    <el-dropdown trigger="click">
                      <span class="el-dropdown-link">
                        更多
                        <el-icon>
                          <ArrowDown />
                        </el-icon>
                      </span>
                      <template #dropdown>
                        <el-dropdown-menu>
                          <el-dropdown-item
                            @click="oneClick(row)"
                            v-has="'programMoreGrouping'"
                            >更改分组</el-dropdown-item
                          >
                          <el-dropdown-item
                            @click="delect(row.id)"
                            v-has="'programSingleDelete'"
                            >删除</el-dropdown-item
                          >
                          <el-dropdown-item
                            @click="openEdit(row.id)"
                            v-has="'programSingledetails'"
                            >发布详情</el-dropdown-item
                          >
                          <el-dropdown-item
                            @click="openEdits(row.id)"
                            v-has="'programEdit'"
                            >编辑</el-dropdown-item
                          >
                        </el-dropdown-menu>
                      </template>
                    </el-dropdown>
                  </div>
                </template>
              </el-table-column>
            </el-table>
            <el-dialog
              @close="verify"
              v-model="isGroupingDialogs"
              :close-on-press-escape="false"
              title="选择分组"
              width="25%"
            >
              <el-form
                ref="equipFormRef"
                :model="equipForm"
                :rules="equipRules"
                label-position="left"
                label-width="70px"
              >
                <el-form-item label="设备组" prop="eEquipName">
                  <div class="-addDialogFormInput e-l-cascader">
                    <el-cascader
                      ref="cascader"
                      v-model="equipForm.eEquipName"
                      :options="trees"
                      :props="regionProps"
                      clearable
                      placeholder="请选择设备组"
                      @change="getCheckedNode"
                    />
                  </div>
                </el-form-item>
              </el-form>
              <template #footer>
                <span>
                  <el-button @click="isGroupingDialogs = false">取消</el-button>
                  <el-button
                    type="primary"
                    @click="submitChangeGroupings(equipFormRef)"
                  >
                    确定
                  </el-button>
                </span>
              </template>
            </el-dialog>
            <div class="-pages">
              <el-pagination
                v-model:current-page="currentPage"
                v-model:page-size="pageSize"
                :page-sizes="[10, 20, 30, 40]"
                :total="total"
                background
                layout="total, sizes, prev, pager, next"
                @size-change="handleSizeChange"
                @current-change="handleCurrentChange"
              />
            </div>
            <el-dialog v-model="dialog" title="温馨提示" width="30%">
              <template #header="{ titleId, titleClass }">
                <div class="my-header">
                  <h4
                    :id="titleId"
                    :class="titleClass"
                    style="display: flex; align-items: center"
                  >
                    <div class="add"></div>
                    <div style="margin: 0 5px">温馨提示</div>
                  </h4>
                </div>
              </template>
              <span>删除的节目不支持找回，确定要删除当前节目吗</span>
              <template #footer>
                <span class="dialog-footer">
                  <el-button @click="dialog = false">取消</el-button>
                  <el-button type="primary" @click="dialogs"> 确定 </el-button>
                </span>
              </template>
            </el-dialog>
            <el-dialog
              v-model="dialogFormVisible"
              @close="forEqreClick"
              title="复制"
              width="30%"
            >
              <el-form :model="form" center ref="forEqre">
                <el-form-item label="节目名称:" label-width="140px">
                  <el-input
                    @input="btnAdd"
                    v-model="form.name"
                    autocomplete="off"
                    maxlength="20"
                  />
                  <div v-if="addIN" style="color: red">节目名称不能为空</div>
                </el-form-item>
              </el-form>
              <template #footer>
                <span class="dialog-footer">
                  <el-button @click="dialogFormVisible = false">取消</el-button>
                  <el-button type="primary" @click="ConfirmCopy">
                    确认
                  </el-button>
                </span>
              </template>
            </el-dialog>
          </div>
        </div>
      </div>
    </el-col>
  </el-row>
</template>

<script lang="ts" setup>
import {
  nextTick,
  onMounted,
  reactive,
  ref,
  shallowRef,
  unref,
  watch,
  toRaw,
} from "vue";
import {
  ArrowDown,
  Close,
  CopyDocument,
  EditPen,
  MoreFilled,
  Search,
} from "@element-plus/icons-vue";
import type {
  DropdownInstance,
  FormInstance,
  FormRules,
  CascaderProps,
} from "element-plus";
import { ElMessage, ElMessageBox, ElTable } from "element-plus";
import {
  DelectPrograms,
  programGroupGet,
  programGroup,
  getScene,
} from "@/api/facility";
import {
  programAddList,
  addResolution,
  resolutionList,
  CopyOpenprogram,
  DelectProgram,
  openprogram,
  batchDelectProgram,
  getprogroup,
  getprogroupupdate,
} from "@/api/advertising";
import { convertDatad } from "@/utils/list";
import ClipboardJS from "clipboard";
import router from "@/router";
const cascader = ref("");
const equipFormRef = ref<FormInstance>();
// 复制弹框
const dialogFormVisible = ref(false);
// 复制弹框里面的inoput
const form = reactive({
  name: "",
});
//新增分组
const dialogVisible = shallowRef(false);
const addTreeName = shallowRef("");
const TreeValue = ref("");
//树形控件
const trees = ref<Tree[] | null>(null);
// 更改/删除/发布按钮状态
const dropdownGrouping = ref<DropdownInstance>();
const dropdownDelete = ref<DropdownInstance>();
const releaseDelete = ref<DropdownInstance>();
//新增节目/发布广告
const isUploadMaterial = shallowRef(false);
const formInline = reactive({
  programName: "",
  programType: "",
  programResolution: "",
  programCustom: "", //自定义宽高
  wide: "", //宽
  High: "", //高
});
watch(
  () => formInline,
  (newVal) => {
    if (newVal.wide || newVal.High) {
      formInline.programCustom = `${newVal.wide}x${newVal.High}`;
    } else {
      formInline.programCustom = "";
    }
  },
  { deep: true }
);
const ruleFormRef = ref<FormInstance>();
const rules = reactive<FormRules>({
  programName: [{ required: true, message: "请填写节目名称", trigger: "blur" }],
  programType: [{ required: true, message: "请选择类型", trigger: "change" }],
  programResolution: [
    { required: true, message: "请选择分辨率", trigger: "change" },
  ],
  programCustom: [{ required: true, message: "请输入宽高", trigger: "blur" }],
});
//选择分辨率
const selectValue = shallowRef("");
const options = shallowRef([]);
//日期选择
const dateValue = ref("");
const search = shallowRef("");
//表格数据
var tableData: any = ref([]);
// 获取节目分组列表
const getTreeData = async () => {
  const { data } = await programGroupGet();
  if (data.code !== 1) return ElMessage({ message: data.msg, type: "error" });
  trees.value = convertDatad(data.data);
  TreeValue.value = data.data[0].id;
};
var addIN = ref(false);
const clearAd = () => {
  addTreeName.value = "";
  addIN.value = false;
};
var dialog = ref(false);
// 清空时间选择
const handeclear = () => {
  if (startDate.value == "") {
    startDate.value = "";
    endDate.value = "";
    paging();
  }
};
// 关闭校验
const clearAds = () => {
  ruleFormRef.value.clearValidate();
};
const verify = () => {
  equipFormRef.value.clearValidate();
};
const btnAdd = (val: any) => {
  if (val) {
    addIN.value = false;
  } else {
    addIN.value = true;
  }
};
const userINfo = ref("新增分组");
var edpid = ref("");
var newObj = ref({});
// 新增分组/子分组/编辑分组确定
const onAddTreeName = async () => {
  if (addTreeName.value) {
    addIN.value = false;
  } else {
    addIN.value = true;
  }
  const params = {
    groupName: unref(addTreeName),
    pid: edpid.value ? edpid.value : 0,
  };
  if (userINfo.value == "新增分组") {
    if (addTreeName.value) {
      const { data } = await programGroup(params);
      if (data.code !== 1)
        return ElMessage({ message: data.msg, type: "error", duration: 1000 });
      await getTreeData();
      ElMessage({ message: data.msg, type: "success", duration: 1000 });
      dialogVisible.value = false;
    }
  } else if (userINfo.value == "添加子分组") {
    if (addTreeName.value) {
      const paramss = {
        groupName: unref(addTreeName),
        pid: edpid.value,
      };
      const { data } = await programGroup(paramss);
      if (data.code !== 1)
        return ElMessage({ message: data.msg, type: "error", duration: 1000 });
      await getTreeData();
      ElMessage({ message: data.msg, type: "success", duration: 1000 });
      dialogVisible.value = false;
    }
  } else if (userINfo.value == "编辑分组") {
    getprogroup(newObj.value)
      .then(({ data }) => {
        if (data.code !== 1)
          return ElMessage({
            message: data.msg,
            type: "error",
            duration: 1000,
          });
        getTreeData();
        ElMessage({ message: data.msg, type: "success", duration: 1000 });
        dialogVisible.value = false;
        addTreeName.value = "";
      })
      .catch((e) => {});
  }
};
// 编辑分组
const editStop = (node: any, data: Tree) => {
  addTreeName.value = data.label;
  dialogVisible.value = true;
  userINfo.value = "编辑分组";
  edpid.value = data.value;
  let { label, objectVersionNumber, pid, value } = data;
  newObj.value = {
    pid: pid ? pid.toString() : "0",
    groupName: addTreeName.value ? addTreeName : label,
    id: value,
    objectVersionNumber,
  };
};
// 新增分组按钮
const addBut = () => {
  dialogVisible.value = true;
  userINfo.value = "新增分组";
};
//新增子分组
const addAllNode = (node: any, data: Tree) => {
  dialogVisible.value = true;
  userINfo.value = "添加子分组";
  edpid.value = data.value;
};
const delAllNode = (node: any, data: Tree) => {
  ElMessageBox.confirm("是否确认删除该数据?", "提示", {
    confirmButtonText: "确认",
    cancelButtonText: "取消",
  })
    .then(async () => {
      let { data: res } = await DelectPrograms(data.value);
      if (res.code !== 1) {
        ElMessage({ message: res.msg, type: "error", duration: 1000 });
      } else {
        ElMessage({ message: res.msg, type: "success", duration: 1000 });
      }
      await getTreeData();
    })
    .catch((e) => {
      ElMessage({ message: "取消删除", type: "success", duration: 1000 });
    });
};
//表单部分
const multipleTableRef = ref<InstanceType<typeof ElTable>>();
const multipleSelection = ref<programMsgTable[]>([]);
const id = ref([]);
var list = ref();
//勾选表单时触发
const handleSelectionChange = (val: programMsgTable[]) => {
  list.value = JSON.parse(JSON.stringify(val));
  id.value = list.value.map((a) => a.id);
  multipleSelection.value = val;
};
//新建文件
const submitProgramForm = (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  formEl.validate((valid) => {
    if (valid) {
      const { programName, programType, programResolution, programCustom } =
        formInline;
      let withWideHigh;
      if (programResolution == "zdy") {
        withWideHigh = programCustom.split("x");
        addResolution(withWideHigh[0], withWideHigh[1]).then(({ data }) => {
          if (data.code !== 1)
            return ElMessage({
              message: data.msg,
              type: "error",
              duration: 1000,
            });
        });
      } else {
        withWideHigh = programResolution.split("x");
      }
      let linkGroupParent = JSON.stringify([unref(TreeValue.value)]);
      programAddList(
        unref(TreeValue.value),
        programName,
        programType,
        withWideHigh[0],
        withWideHigh[1],
        linkGroupParent
      ).then(({ data }) => {
        if (data.code !== 1)
          return ElMessage({
            message: data.msg,
            type: "error",
            duration: 1000,
          });
        ElMessage({ message: data.msg, type: "success", duration: 1000 });
        localStorage.setItem("id", data.data.id);
        router.push("/AddProgram");
      });
    }
  });
};
// 新建节目弹框控制
const Addpass = () => {
  isUploadMaterial.value = true;
};
const equipForm = reactive<TscEquip>({
  eNo: "",
  eName: "",
  eEquipName: [],
  eResponsible: "",
  eRegion: [],
  eRegionZh: [],
  eDetailedAddress: "",
  wide: "",
  High: "",
});
const equipRules = reactive<FormRules>({
  eNo: [{ required: true, message: "请输入编号", trigger: "blur" }],
  eName: [{ required: true, message: "请输入名称", trigger: "blur" }],
  eEquipName: [{ required: true, message: "请选择设备分组", trigger: "blur" }],
  eResponsible: [
    { required: true, message: "请输入责任人手机号", trigger: "blur" },
  ],
  eRegion: [{ required: true, message: "请选择所在地区", trigger: "blur" }],
  eDetailedAddress: [
    { required: true, message: "请输入详细地址", trigger: "blur" },
  ],
  High: [{ required: true, message: "请输入宽高", trigger: "blur" }],
});
const regionProps: CascaderProps = {
  expandTrigger: "hover",
  checkStrictly: true,
};
//更改分组回调
const isGroupingDialog = shallowRef(false);
const isGroupingDialogs = shallowRef(false);
const batchGrouping = shallowRef([]);
const changeGrouping = (rows: any) => {
  if (rows) {
    let selectGrouping = unref(multipleTableRef)!.getSelectionRows();
    if (selectGrouping.length > 0) {
      batchGrouping.value = selectGrouping.map((r: any) => r.id);
      isGroupingDialog.value = true;
    } else {
      if (!unref(dropdownGrouping)) return;
      dropdownGrouping.value.handleOpen();
    }
  }
};
const dataInfo = ref("");
const getCheckedNode = async (val: any) => {
  dataInfo.value = cascader.value.getCheckedNodes();
};
const submitChangeGrouping = (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  formEl.validate((valid) => {
    if (valid) {
      const newObj = {
        linkGroup: dataInfo.value[0].data.value,
        ids: unref(batchGrouping),
      };
      getprogroupupdate(newObj).then(({ data }) => {
        if (data.code !== 1)
          return ElMessage({
            message: data.msg,
            type: "error",
            duration: 1000,
          });
        // getList(ruleForm);
        ElMessage({ message: data.msg, type: "success", duration: 1000 });
        equipForm.eEquipName = [];
        isGroupingDialog.value = false;
        paging();
      });
    }
  });
};
// 发布
const releaseTable = (rows: any) => {
  if (list.value) {
    localStorage.setItem("list", JSON.stringify(list.value));
  }
  router.push("/advertising/advertisingPublish");
};
// 单个删除
const delect = async (id: any) => {
  ElMessageBox.confirm("是否确认删除该数据?", "提示", {
    confirmButtonText: "确认",
    cancelButtonText: "取消",
  })
    .then(async () => {
      let res = await DelectProgram(id);
      paging();
      if (res.data.code == 1) {
        ElMessage({ message: res.data.msg, type: "success", duration: 1000 });
      } else {
        ElMessage({ message: res.data.msg, type: "error", duration: 1000 });
      }
    })
    .catch((e) => {
      ElMessage({ message: "取消删除", type: "info", duration: 1000 });
    });
};
const oneInfo = ref();
// 单个修改分组
const oneClick = (val: any) => {
  oneInfo.value = val;
  isGroupingDialogs.value = true;
};
// 发布详情
const openEdit = (val: any) => {
  router.push({ path: "/advertising/ReleaseDetails", query: { val } });
  localStorage.setItem("val", val);
};
// 编辑场景
const openEdits = async (val: any) => {
  router.push({
    path: "/editCarch",
    query: { id: val },
  });
  localStorage.setItem("val", val);
};
const submitChangeGroupings = (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  formEl.validate((valid) => {
    if (valid) {
      const newObj = {
        pid: dataInfo.value[0].data.value,
        ids: [oneInfo.value.id],
      };
      getprogroupupdate(newObj).then(({ data }) => {
        if (data.code !== 1)
          return ElMessage({
            message: data.msg,
            type: "error",
            duration: 1000,
          });
        // getList(ruleForm);
        ElMessage({ message: data.msg, type: "success", duration: 1000 });
        equipForm.eEquipName = [];
        isGroupingDialogs.value = false;
      });
    }
  });
};
//批量删除表单数据
const deleteTable = async (rows: any) => {
  let selectGrouping = unref(multipleTableRef)!.getSelectionRows();
  if (selectGrouping.length > 0) {
    dialog.value = true;
  } else {
    if (!unref(dropdownDelete)) return;
    dropdownDelete.value.handleOpen();
  }
};
const dialogs = async () => {
  let res = await batchDelectProgram(id.value);
  if (res.data.code == 1) {
    ElMessage({ message: res.data.msg, type: "success", duration: 1000 });
    paging();
    dialog.value = false;
  } else {
    ElMessage({ message: res.data.msg, type: "error", duration: 1000 });
  }
};
//table修改文件名
const handleFileName = (rows: any) => {
  rows.isFile = false;
};
//table单挑数据复制
const copyFileName = (text: any) => {
  const clipboard: any = new ClipboardJS(".btn", {
    text: () => text.programName,
  });
  clipboard.on("success", (e: any) => {
    ElMessage({ message: "已复制到剪贴板", type: "success", duration: 1000 });
    e.clearSelection();
  });
  clipboard.on("error", () => {
    ElMessage({ message: "复制失败", type: "error", duration: 1000 });
  });
  clipboard.onClick(event);
};
const texts = ref();
//table复制整条数据弹出按钮
const copyTableObj = (text: any) => {
  dialogFormVisible.value = true;
  texts.value = text;
  paging();
};
//table复制整条数据
const ConfirmCopy = async () => {
  if (form.name) {
    addIN.value = false;
  } else {
    addIN.value = true;
  }
  if (form.name) {
    let res = await CopyOpenprogram(texts.value.id, form.name);
    if (res.data.code == 1) {
      ElMessage({ message: res.data.msg, type: "success", duration: 1000 });
      dialogFormVisible.value = false;
      form.name = "";
      texts.value.id = "";
      paging();
    } else {
      ElMessage({ message: res.data.msg, type: "error", duration: 1000 });
    }
  }
};
var forEqre = ref();
// f复制弹框的取消校验
const forEqreClick = () => {
  form.name = "";
  texts.value.id = "";
  addIN.value = false;
};
var linkGroupId = ref("");
const nodeClick = (id: any) => {
  TreeValue.value = id.value;
  linkGroupId.value = id.value;
  edpid.value = id.value;
  paging();
};
//请求数据
const getResolution = async () => {
  const { data } = await resolutionList();
  if (data.code !== 1)
    return ElMessage({ message: data.msg, type: "error", duration: 1000 });
  options.value = data.data.map((r: any) => {
    return {
      value: `${r.longResolution}x${r.wideResolution}`,
      label: `${r.longResolution}x${r.wideResolution}`,
    };
  });
};
//分页
const currentPage = ref(1);
const pageSize = ref(10);
const wideResolution = ref("");
const longResolution = ref("");
var total = ref();
var startDate = ref("");
var endDate = ref("");
var keyword = ref("");
// 输入素材或者用户名搜索
const inputClick = () => {
  keyword.value = search.value;
  paging();
};
// 选择时间
const TimeClcik = (val: any) => {
  if (val) {
    val[0].setUTCDate(val[0].getUTCDate() + 1);
    startDate.value = val[0].toISOString().substr(0, 10) + " 00:00:00";
    val[1].setUTCDate(val[1].getUTCDate() + 1);
    endDate.value = val[1].toISOString().substr(0, 10) + " 23:59:59";
    paging();
  } else {
    startDate.value = "";
    endDate.value = "";
    paging();
  }
};
// 分辨率搜索
const select = (val: any) => {
  let width = val.label.split("x");
  wideResolution.value = width[0];
  longResolution.value = width[1];
  paging();
};
const clickSelct = () => {
  wideResolution.value = "";
  longResolution.value = "";
  paging();
};
const closeClick = () => {
  wideResolution.value = "";
  longResolution.value = "";
  paging();
};
const paging = async () => {
  let data = {
    pageNum: currentPage.value,
    pageSize: pageSize.value,
    wideResolution: wideResolution.value,
    longResolution: longResolution.value,
    startDate: startDate.value,
    endDate: endDate.value,
    keyword: search.value,
    linkGroup: linkGroupId.value,
  };
  let res = await openprogram(data);
  if (res.data.code == 1) {
    total = res.data.data.totalElements;
    res.data.data.content.forEach((item: any) => {
      // 将 fileSize 从字节转换为兆字节
      item.programSize = (item.programSize / (1024 * 1024)).toFixed(1); // 四舍五入保留两位小数
    });
    tableData.value = res.data.data.content;
  }
};
//pages
const handleSizeChange = (val: number) => {
  pageSize.value = val;
  paging();
};
const handleCurrentChange = (val: number) => {
  currentPage.value = val;
  paging();
};
onMounted(() => {
  getTreeData();
  getResolution();
  paging();
});
</script>

<style lang="scss" scoped>
.add {
  width: 3px;
  height: 20px;

  /* 主色 */

  background: #0daeff;
  border-radius: 3px;

  /* Inside auto layout */

  flex: none;
  order: 0;
  flex-grow: 0;
}
::v-deep .el-date-editor .el-range__close-icon svg {
  vertical-align: middle;
  /* position: sticky; */
  /* left: 5px; */
  margin-right: 14px;
}
::v-deep .el-date-editor .el-range__icon {
  height: inherit;
  font-size: 14px;
  color: var(--el-text-color-placeholder);
  /* float: left; */
  position: fixed;
  right: 7px;
}
::v-deep .el-input input::selection {
  background-color: #79bbff;
}
::v-deep .el-tree-node__content {
  display: flex;
  align-items: center;
  height: 34px;
  cursor: pointer;
}
::v-deep .wrap_right_list--table-content .el-dropdown-link[data-v-7443f3dc] {
  cursor: pointer;
  color: var(--el-color-primary);
  display: flex;
  align-items: center;
  font-size: 12px;
  margin-left: 12px;
  padding: 7px 11px;
  outline: none;
}

.program_flex_box {
  width: 100%;
  height: calc(100vh - 100px);
  font-size: 14px;
}

.wrap_left_grouping {
  width: 20%;
  height: 100%;
  background-color: white;
  border-radius: 10px;
  padding: 15px;
  color: #303233;
  overflow-y: auto;

  &--head-title {
    height: 56px;
    line-height: 56px;
    border-bottom: 1px solid #f6f7f9;
    white-space: nowrap;
    font-weight: 500;
  }

  &--content-area {
    padding: 20px 5px;

    .edit-child-node {
      width: calc(100% - 10px);
      height: 26px;

      :deep(.el-input__wrapper) {
        background: rgba(255, 255, 255, 0.6);
      }
    }
  }
}

.wrap_right_list {
  width: 80%;
  height: 100%;
  background-color: white;
  border-radius: 10px;
  padding: 15px;
  margin-left: 10px;
  overflow: hidden;
  position: relative;

  &--head-title {
    height: 56px;
    line-height: 56px;
    border-bottom: 1px solid #f6f7f9;
    white-space: nowrap;
    font-weight: 500;
  }

  &--head-operation {
    display: flex;
    flex-direction: row;
    align-items: center;
    justify-content: space-between;
    padding: 20px 0;
    overflow: hidden;

    &:hover {
      overflow-x: auto;
    }

    .-row--search {
      display: grid;
      grid-template-areas: "a b c";
    }

    .-dialog-input {
      width: 100%;
      overflow: hidden;

      :deep(.el-form-item__content) {
        max-width: 450px;
      }

      :deep(.el-select) {
        width: 450px;
      }

      .-addDialogFormInput {
        :deep(.el-input) {
          max-width: 190px;
        }
      }
    }
  }

  &--table-content {
    .el-dropdown-link {
      cursor: pointer;
      color: var(--el-color-primary);
      display: flex;
      align-items: center;
      font-size: 12px;
      margin-left: 12px;
      padding: 5px 11px;
      outline: none;
    }

    .file-child-node {
      width: calc(100% - 40px);
      height: 26px;
    }

    :deep(.el-table__row):hover .--table-column-icon {
      display: inline-block;
    }

    .--table-column-icon {
      display: none;
      margin-left: 10px;
      cursor: pointer;

      &:hover {
        :deep(.el-icon) {
          color: var(--el-color-primary);
        }
      }
    }

    .-pages {
      position: absolute;
      left: 50%;
      bottom: 20px;
      transform: translateX(-50%);
    }

    :deep(.is-background .btn-prev) {
      border: 1px solid var(--el-border-color);
      background-color: var(--el-input-bg-color, var(--el-fill-color-blank));
    }

    :deep(.is-background .btn-next) {
      border: 1px solid var(--el-border-color);
      background-color: var(--el-input-bg-color, var(--el-fill-color-blank));
    }

    :deep(.el-pager li) {
      border: 1px solid var(--el-border-color);
      background-color: var(--el-input-bg-color, var(--el-fill-color-blank));
    }
  }
}
</style>
